package cn.chuxing.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;

/**
 * Created by cooper on 2018/1/19.
 */
@Controller
@RequestMapping
public class LoginController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private DefaultKaptcha captchaProducer;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @RequestMapping("/")
    public String init(){
        return "login";
    }

    @RequestMapping("/login")
    public String login(String userName, String password, String code){

        return "index";
    }

    /**
     * 登出
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout() {

        return "/admin/login";
    }

    @RequestMapping("/code.jpg")
    public void getKaptchaImage(HttpServletResponse response) throws Exception{
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control",
                "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        String capText = captchaProducer.createText();
        logger.info("capText: {}" ,capText);

        String uuid = org.thymeleaf.util.StringUtils.randomAlphanumeric(6);
        Cookie cookie = new Cookie(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY, uuid);
        redisTemplate.opsForValue().set(uuid, capText);
        response.addCookie(cookie);

        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }
}
